<template>
  <!-- 加载状态 -->
  <div v-if="loading" class="loading-container">
    <el-skeleton style="width: 100%" animated>
      <template #template>
        <el-skeleton-item variant="p" style="width: 100%; height: 200px" />
        <div style="display: flex; justify-content: space-between; margin-top: 20px">
          <el-skeleton-item variant="p" style="width: 32%" />
          <el-skeleton-item variant="p" style="width: 32%" />
          <el-skeleton-item variant="p" style="width: 32%" />
        </div>
      </template>
    </el-skeleton>
  </div>

  <!-- 错误状态 -->
  <div v-else-if="error" class="error-container">
    <el-empty :description="errorMessage">
      <el-button type="primary" @click="fetchUserInfo">重新加载</el-button>
    </el-empty>
  </div>

  <!-- 内容区域 -->
  <Layout v-else>
    <!-- 欢迎页 -->
    <div class="welcome-section">
      <div class="welcome-card">
        <div class="welcome-header">
          <h2>欢迎回来，{{ userInfo.username || '用户' }}</h2>
          <p class="welcome-time">上次登录时间：{{ formatDateTime(userInfo.lastLoginTime) }}</p>
        </div>
        <div class="balance-info">
          <div class="balance-item">
            <div class="balance-label">账户余额</div>
            <div class="balance-value">¥ {{ formatMoney(userInfo.balance) }}</div>
          </div>
          <div class="balance-item">
            <div class="balance-label">冻结金额</div>
            <div class="balance-value">¥ {{ formatMoney(userInfo.frozenAmount) }}</div>
          </div>
        </div>
        <div class="quick-actions">
          <el-button type="primary" plain @click="router.push('/transfer')">
            <el-icon><Money /></el-icon>转账
          </el-button>
          <el-button type="primary" plain @click="router.push('/bills')">
            <el-icon><Document /></el-icon>账单查询
          </el-button>
          <el-button type="primary" plain @click="router.push('/products')">
            <el-icon><GoodsFilled /></el-icon>金融产品
          </el-button>
          <el-button type="success" plain @click="router.push('/test-products')">
            <el-icon><Tools /></el-icon>测试页面
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 卡片区域 -->
    <div class="dashboard-section">
      <el-row :gutter="20">
        <!-- 账户概览 -->
        <el-col :xs="24" :sm="12" :md="8">
          <div class="dashboard-card">
            <div class="card-header">
              <h3>账户概览</h3>
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="card-content">
              <div class="data-item">
                <div class="data-label">活期账户</div>
                <div class="data-value">¥ {{ formatMoney(userInfo.balance) }}</div>
              </div>
              <div class="data-item">
                <div class="data-label">理财资产</div>
                <div class="data-value">¥ 0.00</div>
              </div>
              <div class="data-item">
                <div class="data-label">贷款额度</div>
                <div class="data-value">¥ 100,000.00</div>
              </div>
            </div>
            <div class="card-footer">
              <el-button link @click="router.push('/accounts')">查看详情</el-button>
            </div>
          </div>
        </el-col>
        
        <!-- 近期交易 -->
        <el-col :xs="24" :sm="12" :md="8">
          <div class="dashboard-card">
            <div class="card-header">
              <h3>近期交易</h3>
              <el-icon><Document /></el-icon>
            </div>
            <div class="card-content">
              <div class="empty-data">
                <el-empty description="暂无交易记录" :image-size="80"></el-empty>
              </div>
            </div>
            <div class="card-footer">
              <el-button link @click="router.push('/bills')">查看全部</el-button>
            </div>
          </div>
        </el-col>
        
        <!-- 理财推荐 -->
        <el-col :xs="24" :sm="12" :md="8">
          <div class="dashboard-card">
            <div class="card-header">
              <h3>理财推荐</h3>
              <el-icon><GoodsFilled /></el-icon>
            </div>
            <div class="card-content">
              <div class="product-item">
                <div class="product-name">活期宝</div>
                <div class="product-rate">年化收益率 3.5%</div>
                <div class="product-desc">灵活存取，随时支取</div>
              </div>
              <div class="product-item">
                <div class="product-name">定期宝</div>
                <div class="product-rate">年化收益率 4.2%</div>
                <div class="product-desc">3个月定期，稳健收益</div>
              </div>
            </div>
            <div class="card-footer">
              <el-button link @click="router.push('/products')">更多产品</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <el-col :xs="24" :md="12">
          <div class="chart-card">
            <div class="card-header">
              <h3>收支统计</h3>
              <el-icon><PieChart /></el-icon>
            </div>
            <div class="chart-container" ref="incomeExpenseChart">
              <!-- 这里将通过echarts渲染图表 -->
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :md="12">
          <div class="chart-card">
            <div class="card-header">
              <h3>资产分布</h3>
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="chart-container" ref="assetDistributionChart">
              <!-- 这里将通过echarts渲染图表 -->
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </Layout>
</template>

<script setup name="UserHomeView">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import { 
  Money, Document, GoodsFilled, Wallet,
  PieChart, DataAnalysis, Tools
} from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user';
import Layout from '@/components/layout/Layout.vue';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart as EchartsPieChart, BarChart, LineChart } from 'echarts/charts';
import { 
  TitleComponent, TooltipComponent, LegendComponent, 
  GridComponent, DatasetComponent, ToolboxComponent
} from 'echarts/components';

// 注册ECharts必要的组件
echarts.use([
  CanvasRenderer, EchartsPieChart, BarChart, LineChart,
  TitleComponent, TooltipComponent, LegendComponent,
  GridComponent, DatasetComponent, ToolboxComponent
]);

// 路由和状态管理
const router = useRouter();
const userStore = useUserStore();

// 加载状态
const loading = ref(true);
const error = ref(false);
const errorMessage = ref('加载失败，请重试');
const userInfo = reactive({
  username: '',
  balance: 0,
  frozenAmount: 0,
  avatar: '',
  lastLoginTime: null
});

// 图表引用
const incomeExpenseChart = ref(null);
const assetDistributionChart = ref(null);
let incomeExpenseChartInstance = null;
let assetDistributionChartInstance = null;

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true;
  error.value = false;
  
  try {
    // 如果有用户信息则使用
    if (userStore.userInfo) {
      Object.assign(userInfo, userStore.userInfo);
    } else {
      // 否则尝试获取用户信息
      await userStore.getUserInfoAction();
      if (userStore.userInfo) {
        Object.assign(userInfo, userStore.userInfo);
      } else {
        throw new Error('获取用户信息失败');
      }
    }
    
    // 延迟切换加载状态，避免闪烁
    setTimeout(() => {
      loading.value = false;
    }, 300);
  } catch (err) {
    console.error('获取用户信息失败:', err);
    loading.value = false;
    error.value = true;
    errorMessage.value = '获取用户信息失败，请重试';
    
    // 检查是否是未登录状态
    if (err.message && (err.message.includes('401') || err.message.includes('登录') || err.message.includes('未授权'))) {
      ElMessage.error('未登录或登录已过期，请重新登录');
      Cookies.remove('virtual_bank_token');
      Cookies.remove('token');
      
      // 延迟跳转，给用户看到提示的时间
      setTimeout(() => {
        window.location.href = '/login';
      }, 1500);
    }
  }
};

// 日期时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return '暂无数据';
  
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 金额格式化
const formatMoney = (amount) => {
  if (amount === undefined || amount === null) return '0.00';
  return parseFloat(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 初始化收支统计图表
const initIncomeExpenseChart = () => {
  if (incomeExpenseChart.value) {
    incomeExpenseChartInstance = echarts.init(incomeExpenseChart.value);
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['收入', '支出']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '收入',
          type: 'bar',
          emphasis: {
            focus: 'series'
          },
          data: [3200, 4500, 5000, 3800, 4200, 6000],
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '支出',
          type: 'bar',
          emphasis: {
            focus: 'series'
          },
          data: [2800, 3900, 4200, 3500, 3800, 4500],
          itemStyle: {
            color: '#F56C6C'
          }
        }
      ]
    };
    
    incomeExpenseChartInstance.setOption(option);
  }
};

// 初始化资产分布图表
const initAssetDistributionChart = () => {
  if (assetDistributionChart.value) {
    assetDistributionChartInstance = echarts.init(assetDistributionChart.value);
    
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['活期存款', '定期存款', '股票投资', '基金投资', '其他资产']
      },
      series: [
        {
          name: '资产分布',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 50000, name: '活期存款', itemStyle: { color: '#409EFF' } },
            { value: 30000, name: '定期存款', itemStyle: { color: '#67C23A' } },
            { value: 20000, name: '股票投资', itemStyle: { color: '#E6A23C' } },
            { value: 15000, name: '基金投资', itemStyle: { color: '#F56C6C' } },
            { value: 8000, name: '其他资产', itemStyle: { color: '#909399' } }
          ]
        }
      ]
    };
    
    assetDistributionChartInstance.setOption(option);
  }
};

// 处理窗口大小变化，重新渲染图表
const handleResize = () => {
  if (incomeExpenseChartInstance) {
    incomeExpenseChartInstance.resize();
  }
  if (assetDistributionChartInstance) {
    assetDistributionChartInstance.resize();
  }
};

// 初始化图表 (仅在用户信息加载成功后)
const initCharts = () => {
  setTimeout(() => {
    initIncomeExpenseChart();
    initAssetDistributionChart();
  }, 300);
};

onMounted(async () => {
  // 如果是从通过浏览器后退按钮到达此页面，重新获取用户信息
  if (window.performance && window.performance.navigation.type === 2) {
    // 重新刷新用户信息
    await fetchUserInfo();
  } else {
    // 获取用户信息
    await fetchUserInfo();
  }
  
  // 仅在用户信息加载成功后初始化图表
  if (!error.value) {
    initCharts();
  }
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 销毁图表实例
  if (incomeExpenseChartInstance) {
    incomeExpenseChartInstance.dispose();
  }
  
  if (assetDistributionChartInstance) {
    assetDistributionChartInstance.dispose();
  }
});
</script>

<style scoped>
.loading-container,
.error-container {
  min-height: 100vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.welcome-section {
  margin-bottom: 20px;
}

.welcome-card {
  background: linear-gradient(135deg, #1e3c72, #2a5298);
  color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.welcome-header {
  margin-bottom: 15px;
}

.welcome-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.welcome-time {
  margin: 8px 0 0;
  opacity: 0.8;
  font-size: 14px;
}

.balance-info {
  display: flex;
  margin-bottom: 24px;
}

.balance-item {
  flex: 1;
}

.balance-label {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.balance-value {
  font-size: 24px;
  font-weight: 700;
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.dashboard-section {
  margin-bottom: 20px;
}

.dashboard-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.card-content {
  margin-bottom: 15px;
  min-height: 150px;
}

.data-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.data-label {
  color: #606266;
}

.data-value {
  font-weight: 600;
  color: #303133;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 150px;
}

.product-item {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 10px;
}

.product-name {
  font-weight: 600;
  margin-bottom: 5px;
}

.product-rate {
  color: #e6a23c;
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 5px;
}

.product-desc {
  color: #909399;
  font-size: 12px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  height: 100%;
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-header h2 {
    font-size: 20px;
  }
  
  .balance-info {
    flex-direction: column;
  }
  
  .balance-item {
    margin-bottom: 15px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>
